#import "QKNetWorkTools.h"
#import <CFNetwork/CFNetwork.h>
#import "AFNetworking.h"
@implementation QKNetWorkTools
#ifdef DEBUG //调试

#define NSLog(FORMAT, ...) fprintf(stderr, "%s:%zd\t%s\n", [[[NSString stringWithUTF8String: __FILE__] lastPathComponent] UTF8String], __LINE__, [[NSString stringWithFormat: FORMAT, ## __VA_ARGS__] UTF8String]);

#else // 发布

#define NSLog(FORMAT, ...) nil

#endif

+ (void)getGuWenJsonWithURLString:(NSString *)URLString
                          params:(NSDictionary *)params
                         isPrint:(BOOL)isprint
                         success:(void (^)(id responseObject))success
                          failure:(void (^)(NSError *error))failure{

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSDictionary *header = @{@"User-Agent": @"CFNetwork/758.2.9", @"login": @"false", @"accept-language": @"zh-cn"};
    NSData *headerData = [NSJSONSerialization dataWithJSONObject:header options:0 error:nil];
    NSString *headerString = [[NSString alloc] initWithData:headerData encoding:NSUTF8StringEncoding];
    manager.responseSerializer.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"text/html",@"application/json",@"application/x-www-form-urlencoded",@"text/json",nil];
    [manager.requestSerializer setTimeoutInterval:30];
    [manager.requestSerializer setValue:headerString forHTTPHeaderField:@"head"];
    NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
    [cookieProperties setObject:@"58FED5B014C347EDFE1C9AD62460D0D358CA9D3E61418469E335AC0068FD2EE20ACF44F1265569A2"forKey:@"yhid"];
    [cookieProperties setObject:@"F09B42CF0078D3FA7EC70B92C48AF2F5FEA93E1CA1EA4EFE4508A9521559604EF6BF1E993FAF261CCCD3DDB3B2C749A8D607F5CBF049B34F"forKey:@"yhpwd"];
    NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];

    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    [manager GET:URLString parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
#ifdef DEBUG
            if (isprint) {
                NSLog(@"\n***********************************************\n请求成功:URL:%@ \n 参数：%@, \n obj:%@ \n***********************************************",URLString,params,responseObject);
            }
#endif
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
#ifdef DEBUG
            if (isprint) {
                NSLog(@"\n***********************************************\n请求失败:URL:%@ \n 参数：%@, \n Error:%@ \n***********************************************",URLString,params,error);
            }
#endif
    }];

}

+ (BOOL)getProxyStatus {
//    return NO;
    NSDictionary *proxySettings =  (__bridge NSDictionary *)(CFNetworkCopySystemProxySettings());
    NSArray *proxies = (__bridge NSArray *)(CFNetworkCopyProxiesForURL((__bridge CFURLRef _Nonnull)([NSURL URLWithString:@"http://www.baidu.com/"]), (__bridge CFDictionaryRef _Nonnull)(proxySettings)));
    NSDictionary *settings = [proxies objectAtIndex:0];

    NSLog(@"host=%@", [settings objectForKey:(NSString *)kCFProxyHostNameKey]);
    NSLog(@"port=%@", [settings objectForKey:(NSString *)kCFProxyPortNumberKey]);
    NSLog(@"type=%@", [settings objectForKey:(NSString *)kCFProxyTypeKey]);

    if ([[settings objectForKey:(NSString *)kCFProxyTypeKey] isEqualToString:@"kCFProxyTypeNone"]){
        //没有设置代理
        return NO;
    }else{

        //设置代理了
        return YES;
    }
}


+ (void)uploadWithURLString:(NSString *)URLString
                   fileData:(NSData *)fileData
                    progress:(void (^)(NSProgress *uploadProgress))progress
                    success:(void (^)(id _Nonnull))success
                    failure:(void (^)(NSError * _Nonnull))failure{
    AFHTTPSessionManager  *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"text/html",@"application/json",@"application/x-www-form-urlencoded",@"text/json",nil];
    [mgr.requestSerializer setTimeoutInterval:30];
    
    [mgr POST:URLString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:fileData name:@"file" fileName:@"mine.jpg" mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        progress(uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
}

+ (void)getparamStringWithURLString:(NSString *)URLString
                   params:(NSString *)params
                  isPrint:(BOOL)isprint
                  success:(void (^)(id responseObject))success
                  failure:(void (^)(NSError *error))failure
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString]];
    [request setHTTPMethod:@"GET"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    if (params !=nil) {
        [request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
    }
    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"%@",error);
            failure(error);
#ifdef DEBUG
            if (isprint) {
                NSLog(@"\n***********************************************\n请求失败:URL:%@ \n 参数：%@, \n Error:%@ \n***********************************************",URLString,params,error);
            }
#endif
        }else{
            NSError *error;
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
            if (!error) {
                success(dict);
#ifdef DEBUG
                if (isprint) {
                    NSString *paramStr = nil;
                    if (params!=nil) {
                         paramStr =[[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:params options:0 error:nil] encoding:NSUTF8StringEncoding];
                    }
                    NSString *jsonStr =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                    NSLog(@"\n***********************************************\n 请求成功:URL:%@ \n 参数：%@, \n 返回值:\n%@ \n***********************************************",URLString,paramStr,jsonStr);
                }
#endif
            }else{
                failure(error);
#ifdef DEBUG
                if (isprint) {
                    NSLog(@"\n***********************************************\n请求失败:URL:%@ \n 参数：%@, \n Error:%@ \n***********************************************",URLString,params,error);
                }
#endif
            }
        }
    }];
    [task resume];
}


+ (void)getjsonStringWithURLString:(NSString *)URLString
                   params:(NSDictionary *)params
                  isPrint:(BOOL)isprint
                  success:(void (^)(id responseObject))success
                  failure:(void (^)(NSError *error))failure
{
    URLString = [URLString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString]];
    [request setHTTPMethod:@"GET"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    if (params !=nil) {
        [request setHTTPBody:[NSJSONSerialization dataWithJSONObject:params options:0 error:nil]];
    }
    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"%@",error);
            failure(error);
#ifdef DEBUG
            if (isprint) {
                NSLog(@"\n***********************************************\n请求失败:URL:%@ \n 参数：%@, \n Error:%@ \n***********************************************",URLString,params,error);
            }
#endif
        }else{
            NSError *error;
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
            if (!error) {
                success(dict);
#ifdef DEBUG
                if (isprint) {
                    NSString *paramStr = nil;
                    if (params!=nil) {
                         paramStr =[[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:params options:0 error:nil] encoding:NSUTF8StringEncoding];
                    }
                    NSString *jsonStr =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                    NSLog(@"\n***********************************************\n 请求成功:URL:%@ \n 参数：%@, \n 返回值:\n%@ \n***********************************************",URLString,paramStr,jsonStr);
                }
#endif
            }else{
                failure(error);
#ifdef DEBUG
                if (isprint) {
                    NSLog(@"\n***********************************************\n请求失败:URL:%@ \n 参数：%@, \n Error:%@ \n***********************************************",URLString,params,error);
                }
#endif
            }
        }
    }];
    [task resume];
}

+ (void)postjsonStringWithURLString:(NSString *)URLString
                   params:(NSDictionary *)params
                  isPrint:(BOOL)isprint
                  success:(void (^)(id responseObject))success
                  failure:(void (^)(NSError *error))failure
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    if (params !=nil) {
        [request setHTTPBody:[NSJSONSerialization dataWithJSONObject:params options:0 error:nil]];
    }
    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"%@",error);
            failure(error);
#ifdef DEBUG
            if (isprint) {
                NSLog(@"\n***********************************************\n请求失败:URL:%@ \n 参数：%@, \n Error:%@ \n***********************************************",URLString,params,error);
            }
#endif
        }else{
            NSError *error;
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
            if (!error) {
                success(dict);
#ifdef DEBUG
                if (isprint) {
                    NSString *paramStr = nil;
                    if (params!=nil) {
                         paramStr =[[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:params options:0 error:nil] encoding:NSUTF8StringEncoding];
                    }
                    NSString *jsonStr =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                    NSLog(@"\n***********************************************\n 请求成功:URL:%@ \n 参数：%@, \n 返回值:\n%@ \n***********************************************",URLString,paramStr,jsonStr);
                }
#endif
            }else{
                failure(error);
#ifdef DEBUG
                if (isprint) {
                    NSLog(@"\n***********************************************\n请求失败:URL:%@ \n 参数：%@, \n Error:%@ \n***********************************************",URLString,params,error);
                }
#endif
            }
        }
    }];
    [task resume];
}
+ (void)postWithURLString:(NSString *)URLString
                             params:(NSDictionary *)params
                            isPrint:(BOOL)isprint
                            success:(void (^)(id responseObject))success
                            failure:(void (^)(NSError *error))failure
{
    AFHTTPSessionManager  *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/json",@"text/json",@"application/x-www-form-urlencoded",@"text/javascript",nil];
    [mgr.requestSerializer setTimeoutInterval:60];
    [mgr POST:URLString parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
        #ifdef DEBUG
        if (isprint) {
            NSString *jsonStr =[[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:responseObject options:0 error:nil] encoding:NSUTF8StringEncoding];
            NSString *paramStr = @"";
            if (params != nil) {
                paramStr =[[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:params options:0 error:nil] encoding:NSUTF8StringEncoding];
            }
           
            NSLog(@"\n***********************************************\n 请求成功:URL:%@ \n 参数：%@, \n 返回值:\n%@ \n***********************************************",URLString,paramStr,jsonStr);
        }
        #endif
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure){
            failure(error);
        }
#ifdef DEBUG
        if (isprint) {
            NSLog(@"\n***********************************************\n请求失败:URL:%@ \n 参数：%@, \n Error:%@ \n***********************************************",URLString,params,error);
        }
#endif
    }];
}


+ (void)getWithURLString:(NSString *)URLString
                   params:(NSDictionary *)params
                  isPrint:(BOOL)isprint
                  success:(void (^)(id responseObject))success
                  failure:(void (^)(NSError *error))failure
{
//    URLString = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    AFHTTPSessionManager  *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"text/plain", @"text/html",@"text/json", @"application/json",@"text/javascript",@"application/x-www-form-urlencoded",nil];
    [mgr.requestSerializer setTimeoutInterval:30];
    [mgr GET:URLString parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
#ifdef DEBUG
        if (isprint) {
            NSString *jsonStr =[[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:responseObject options:0 error:nil] encoding:NSUTF8StringEncoding];
            NSString *paramStr = @"";
            if (params !=nil) {
                NSString *paramStr =[[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:params options:0 error:nil] encoding:NSUTF8StringEncoding];
            }
            
            NSLog(@"\n***********************************************\n 请求成功:URL:%@ \n 参数：%@, \n 返回值:\n%@ \n***********************************************",URLString,paramStr,jsonStr);
        }
#endif
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure){
            failure(error);
        }
#ifdef DEBUG
        if (isprint) {
            NSLog(@"\n***********************************************\n请求失败:URL:%@ \n 参数：%@, \n Error:%@ \n***********************************************",URLString,params,error);
        }
#endif
    }];
}


@end
